<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表单设计</title>
    <style>
        #tableForm td {
            height: 34px;

        }

        .form-container {
            position: relative;
            width: 100%;
            height: 100%;
            border: 1px solid #aaa;
        }

        .form-container > div {
            position: absolute;
            top: 0;
            left: 0;
            height: 100%;
            width: 100%;
        }

        .form-container > div:first-child {
            z-index: 100;
            width: 120px;
            background-color: #eee;
            border-right: 1px solid #aaa;

        }

        .form-container > div:last-child {
            z-index: 100;
            width: 210px;
            padding: 10px;

            border-left: 1px solid #aaa;
            right: 0;
            left: auto;
        }

        .divItem {
            width: 100%;
            position: relative;
            height: 45px;
            padding: 5px;
            border-bottom: 1px solid #999;
        }

        .divItem:last-child {
            height: 60px;
        }

        .divItem > input, .divItem > select, .divItem > textarea {
            width: 110px;
            z-index: 10;
            position: absolute;
        }

        .divItem > div:first-child {
            width: 100%;
            position: absolute;
            top: -8px;
        }

        .divItem > div:last-child {
            width: 100%;
            position: absolute;
            height: 100%;
            z-index: 100;
            top: 0;
            left: 0
        }

        .divItem > div:last-child:hover {
            background-color: #00a0e9;
            opacity: 0.2;
        }

        div .select {
            border: 1px solid #0072c6 !important;
            -webkit-box-shadow: 0 0 10px 15px #0CC;
            -moz-box-shadow: 0 0 10px 15px #0CC;
            box-shadow: 0 0 4px 4px #0072c6;
            border-spacing: 4px;
        }

        .table-select {
            /*border: 1px solid #0072c6;*/
            box-shadow: 0 0 4px 4px #0072c6 !important; /**/
            border-collapse: separate;
        }

        .table .select {
            border-collapse: separate !important;
            z-index: 100;
        }

        .table .select + th:first-child {
            border-spacing: 4px;
        }

        .table-select td {
            padding: 2px 5px;
            border-collapse: separate
        }

        #container td {
            height: 30px;
        }

        .drap-down {
            width: 100%;
            height: 10px;
        }

        legend {
            margin-bottom: 0px !important;
        }
    </style>
    <script src="/assets/js/workflow/js/designer/code/Guid.js"></script>
</head>
<body>


<div class="container-fluid" style="height: 100%">
    <div class="row" style="height: 100%">
        <div class="col-lg-12 col-sm-12 col-xs-12" style="height: 100%">
            <div class="widget  no-padding" style="height: 100%; position: relative ; width: 100%; margin-bottom: 0">
                <div class="widget-header bg-themeprimary" style="z-index: 2; width: 100%;">
                    <i class="widget-icon typcn typcn-th-list"></i>
                    <span class="widget-caption">表单设计</span>
                    <div class="toolbar">
                        <a id="btnSave">
                            <i class="glyphicon glyphicon-floppy-disk"></i>保存
                        </a>
                        <a id="btnBack">
                            <i class="fa fa-chevron-left"></i>返回
                        </a>
                    </div>
                </div>
                <div class="widget-body"
                     style="height: 100%; padding-top: 50px; position: absolute;top:0; z-index: 0; width: 100%; border: 1px solid #aaa">
                    <div class="form-container" style="position: relative;">
                        <div class="toolbar" style="position: absolute;" id="divTools">
                            <div>
                                <div id="toolBar">
                                    <div title="form" class="divItem" draggable="true"
                                         ondragstart="drag(event,this,true)" data-type="form">
                                        <form class="form-control">form</form>
                                        <div></div>
                                    </div>
                                    <div title="table" class="divItem" draggable="true"
                                         ondragstart="drag(event,this,true)" data-type="table">
                                        <table class="table table-striped table-bordered table-hover dataTable no-footer">
                                            <tbody>
                                            <tr>
                                                <td></td>
                                                <td></td>
                                                <td></td>
                                            </tr>
                                            <tr>
                                                <td></td>
                                                <td></td>
                                                <td></td>
                                            </tr>

                                            </tbody>
                                        </table>
                                        <div></div>
                                    </div>


                                    <div title="text" class="divItem" draggable="true"
                                         ondragstart="drag(event,this,true)"
                                         data-type="text">
                                        <input class="form-control" type="text" value="text"/>
                                        <div></div>
                                    </div>
                                    <div title="select" class="divItem" draggable="true"
                                         ondragstart="drag(event,this,true)"
                                         data-type="select">
                                        <select class="form-control"></select>
                                        <div></div>
                                    </div>

                                    <div title="checkbox" class="divItem" draggable="true"
                                         ondragstart="drag(event,this,true)"
                                         data-type="check">
                                        <div class="checkbox">
                                            <label style="color:#222;">
                                                <input class="colored-success" type="checkbox">
                                                <span class="text">checkbox</span>
                                            </label>
                                        </div>
                                        <div></div>
                                    </div>
                                    <div title="radio" class="divItem" draggable="true"
                                         ondragstart="drag(event,this,true)"
                                         data-type="radio">
                                        <div class="checkbox">
                                            <label style="color:#222;">
                                                <input class="colored-success" type="radio">
                                                <span class="text">radio</span>
                                            </label>
                                        </div>
                                        <div></div>
                                    </div>


                                    <div title="textarea" class="divItem" draggable="true"
                                         ondragstart="drag(event,this,true)"
                                         data-type="textarea">
                                        <textarea class="form-control" rows="2">textarea</textarea>
                                        <div></div>
                                    </div>

                                </div>
                            </div>
                        </div>
                        <div style="position: absolute; padding: 0 220px  0 130px; z-index: 10;background-color: #eee;">
                            <div id="container" ondrop="dropform(event,this)"
                                 ondragover='allow(event,this,false)' ondragenter='allowDropFrom(event,this,false)'
                                 style="width: 100%; height: 100%;overflow-y: auto;"
                                 ondragleave="dragleave(event,this)">

                            </div>
                        </div>
                        <div style="overflow-y: auto;">
                            <form id="formMainTable" role="form">
                                <div class="form-group">
                                    <label for="remark">描述</label>
                                    <input name="remark" class="form-control input-xs" id="remark" type="text"
                                           placeholder=""/>
                                </div>
                                <div class="form-group">
                                    <label for="formName">Form Name</label>
                                    <input name="formName" class="form-control input-xs" id="formName" type="text"
                                           placeholder=""/>
                                </div>
                                <div class="form-group">
                                    <label for="colNum">列数</label>
                                    <input name="colNum" class="form-control input-xs" id="colNum" type="text"
                                           placeholder=""/>
                                </div>
                                <div style="display: none">
                                    <table class="table table-striped table-bordered table-hover dataTable no-footer">
                                        <thead>
                                        <tr>
                                            <th>模板名称</th>
                                            <th>读</th>
                                            <th>写</th>
                                        </tr>
                                        </thead>
                                        <tbody id="templateConfig">

                                        </tbody>
                                    </table>

                                </div>
                                <div style="display: none;">
                                    <input type="reset"/>
                                </div>
                            </form>
                            <form id="formControl" style="display: none" role="form">
                                <div class="form-group">
                                    <label for="fieldName">名称</label>
                                    <input name="fieldName" class="form-control input-xs" id="fieldName" type="text"
                                           placeholder="">
                                </div>
                                <div class="form-group">
                                    <label for="fieldDbName">数据库字段</label>
                                    <input name="fieldDbName" class="form-control input-xs" id="fieldDbName" type="text"
                                           placeholder="">
                                </div>
                                <div class="form-group">
                                    <label for="isTitle">是否流程标题</label>
                                    <select name="isTitle" class="form-control input-xs" id="isTitle" type="text">
                                        <option value="">请选择</option>
                                        <option value="1">是</option>
                                        <option value="0">否</option>
                                    </select>

                                </div>
                                <div class="form-group">
                                    <label for="dataType">数据类型</label>
                                    <select name="dataType" class="form-control input-xs" id="dataType" type="text">
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="required">是否必填</label>
                                    <select name="required" class="form-control input-xs" id="required" type="text">
                                        <option value="">请选择</option>
                                        <option value="1">是</option>
                                        <option value="0">否</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="colspan">列跨度</label>
                                    <input name="colspan" class="form-control input-xs" id="colspan" type="text"
                                           placeholder="">
                                </div>
                                <div style="display: none;" id="divData">
                                    <fieldset>
                                        <legend>
                                            <div class="checkbox">
                                                <label style="color:#222;">
                                                    <input data-index="0" name="radio" class="colored-success"
                                                           type="radio">
                                                    <span class="text">基础数据</span>
                                                </label>
                                            </div>
                                        </legend>
                                        <div style="display: none;">
                                            <div class="form-group">
                                                <select id="mabiao" name="param" class="form-control input-xs"
                                                        type="text"/>
                                            </div>

                                        </div>
                                    </fieldset>

                                    <fieldset>
                                        <legend>
                                            <div class="checkbox">
                                                <label style="color:#222;">
                                                    <input data-index="1" name="radio" class="colored-success"
                                                           type="radio">
                                                    <span class="text">数据请求</span>
                                                </label>
                                            </div>
                                        </legend>
                                        <div style="display: none;">
                                            <div class="form-group">
                                                <label for="action">请求地址</label>
                                                <input name="action" class="form-control input-xs" id="action"
                                                       type="text" placeholder="请求地址">
                                            </div>
                                            <div class="form-group">
                                                <label for="fieldText">Field Text</label>
                                                <input name="fieldText" class="form-control input-xs" id="fieldText"
                                                       type="text" placeholder="ActionCode">
                                            </div>
                                            <div class="form-group">
                                                <label for="fieldValue">Field Value</label>
                                                <input name="fieldValue" class="form-control input-xs" id="fieldValue"
                                                       type="text" placeholder="ActionCode">
                                            </div>
                                            <div class="form-group">
                                                <label for="fieldValue">参数</label>
                                                <textarea rows="5" class="form-control input-xs"
                                                          name="param1"></textarea>
                                            </div>
                                        </div>
                                    </fieldset>
                                    <fieldset>
                                        <legend>
                                            <div class="checkbox">
                                                <label style="color:#222;">
                                                    <input data-index="2" name="radio" class="colored-success"
                                                           type="radio">
                                                    <span class="text">自定义数据</span>
                                                </label>
                                            </div>
                                        </legend>
                                        <div style="display: none;">
                                            <div class="form-group">
                                                <label for="key">键</label>
                                                <input name="key" class="form-control input-xs" id="key" type="text"
                                                       placeholder="键">
                                            </div>
                                            <div class="form-group">
                                                <label for="nameCollect">值</label>
                                                <input name="nameCollect" class="form-control input-xs" id="nameCollect"
                                                       type="text" placeholder="值">
                                            </div>
                                            <a class="btn" id="addItem">添加</a>
                                            <div>
                                                <table id="tableList"
                                                       class="table table-striped table-bordered table-hover dataTable no-footer ">
                                                    <thead>
                                                    <tr>
                                                        <th>键</th>
                                                        <th>值</th>
                                                        <th>操作</th>
                                                    </tr>
                                                    </thead>
                                                    <tbody>

                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </fieldset>
                                </div>
                                <div style="display: none;">
                                    <input type="reset"/>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div id="divTemplate" style="display: none">
    <div id="formTemplate">
        <div class="widget" style=" position: relative ; width: 100%; margin: 10px 0">
            <div class="widget-header bg-themeprimary" style="z-index: 2; width: 100%;">
                <i class="widget-icon typcn typcn-th-list"></i>
                <span class="widget-caption">Form</span>
            </div>
            <div class="widget-body">
                <div data-target="top" style="width: 100%; height: 10px;" ondrop='dropAddrow(event,this)'
                     ondragover='allow(event,this)' ondragenter='allowDropContainer(event,this)'
                     ondragleave="dragleave(event,this)"></div>
                <form>
                    <table class="table table-striped table-bordered table-hover dataTable no-footer">
                        <tbody>
                        <tr>
                        </tr>
                        </tbody>
                    </table>
                </form>
                <div class="drap-down" data-target="bottom" ondrop='dropAddrow(event,this)'
                     ondragover='allow(event,this)' ondragenter='allowDropContainer(event,this)'
                     ondragleave="dragleave(event,this)"></div>
            </div>
        </div>
    </div>
    <div id="tableTemplate">
        <table style="width: 100%;" draggable="true" ondragstart="drag(event,this)">
            <tbody>
            <tr>
                <td data-target="left" ondrop='drop(event,this)'
                    ondragover='allow(event,this)' ondragenter='allowDrop(event,this)'
                    ondragleave="dragleave(event,this)" style="width:150px;padding-left: 15px;"></td>
                <td data-target="right" ondrop='drop(event,this)'
                    ondragover='allow(event,this)' ondragenter='allowDrop(event,this)'
                    ondragleave="dragleave(event,this)" style="width: auto; padding-right: 5px;"></td>
            </tr>
            </tbody>
        </table>
    </div>
    <div id="subTableTemplate">
        <div draggable="true" data-role="subTableTemplate" ondragstart="drag(event,this)">
            <div>
                <table style="border-collapse: separate;border-spacing: 4px;"
                       class="table table-striped table-bordered table-hover dataTable no-footer">
                    <thead>
                    <tr>
                        <th ondrop='dropAddCol(event,this)' ondragover='allow(event,this)'
                            ondragenter='allowDrop(event,this)'
                            ondragleave="dragleave(event,this)">操作
                        </th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr>
                        <td style="width: 120px;">
                            <a class="btn-search-button" href="#" rel="editRow" data-type="button"><i
                                    class="glyphicon glyphicon-edit"></i>编辑</a>
                            <a class="btn-search-button" href="#" rel="deleteRow" data-type="button"><i
                                    class="glyphicon glyphicon-remove"></i>删除</a>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
            <div class="drap-down" data-target="bottom" ondrop='dropAddrow(event,this)'
                 ondragover='allow(event,this)' ondragenter='allowDropContainer(event,this)'
                 ondragleave="dragleave(event,this)"></div>
        </div>
    </div>

    <div id="subForm">
        <div class="modal fade form bs-example-modal-md" role="dialog" aria-hidden="true">
            <form>
                <div class="modal-dialog modal-md ">
                    <div class="modal-content">

                    </div>
                </div>
            </form>
        </div>
    </div>

    <div id="tdTemplate">

        <div class="checkbox">
            <label style="color:#222;">
                <input class="colored-success" type="checkbox"/>
                <span class="text">  </span>
            </label>
        </div>

    </div>

    <div id="formcontrolContainer">
        <label class="col-sm-1 col-lg-1 col-md-1 col-xs-3 control-label no-padding-right"></label>
        <div></div>
    </div>

    <div id="btnSubmit">
        <div class="form-group">
            <div class="col-sm-offset-8 col-sm-4" style="text-align: right;">
                <a class="btn btn-success" href="#"><i class="fa fa-check right"></i>保存</a>
                <a class="btn btn-danger" href="#" data-dismiss="modal"><i class="fa fa-times right"></i>关闭</a>
            </div>
        </div>
        <input style="display: none;" type="reset" value="重置">
    </div>


    <div id="controlTemplate">
        <div class="col-lg-2 col-sm-2 col-md-2 col-xs-12">
            <div class="checkbox">
                <label style="color:#222;">
                    <input class="colored-success" type="checkbox">
                    <span class="text">checkbox</span>
                </label>
            </div>
        </div>
        <div class="col-lg-2 col-sm-2 col-md-2 col-xs-12">
            <div class="checkbox">
                <label style="color:#222;">
                    <input class="colored-success" type="radio">
                    <span class="text">radio</span>
                </label>
            </div>
        </div>
    </div>
</div>

<div id="generateModal" class="modal fade form bs-example-modal-md" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="widget no-padding">
                <div class="widget-header bg-themeprimary">
                    <i class="widget-icon fa fa-user"></i>
                    <span class="widget-caption"></span>
                    <div class="widget-buttons">
                        <a tabindex="7" data-type="reset"><i class="fa fa-refresh"></i></a>
                        <a data-dismiss="modal">
                            <i class="fa fa-times"></i>
                        </a>
                    </div>
                </div>
                <div class="widget-body">
                    <form class="form-horizontal">

                    </form>
                </div>
            </div>
        </div>
    </div>
</div>


<div style="display: none" id="divGenerate"></div>


<script>
    var formName, controlName, controlTemplate = $("#controlTemplate").children();

    var validate = {}, gridparms = {};
    var deleteObj = [];
    var instanceName;
    var DragType = {
        add: 1,
        move: 0
    }


    var saveresult = {
        result: true,
        message: ''
    }

    var formcontrolContainer = $("#formcontrolContainer"), form_label = formcontrolContainer.children().eq(0), form_control = formcontrolContainer.children().eq(1);
    var style = "col-lg-{0} col-sm-{0} col-md-{0} col-xs-9", size = [4, 6, 8, 12];

    var _rowNum, currentForm, candrop;
    var dragType;
    var tags = [{value: 0, name: 'text', type: 'input'},
        {value: 1, name: 'textarea', type: 'textarea'},
        {value: 2, name: 'select', type: 'select'}];
    var datatypes = [
        {value: 0, name: 'string'},
        {value: 1, name: 'int'},
        {value: 2, name: 'decimal'},
        {value: 3, name: 'date'}];
    var templateConfig;

    var dropfinish, dragleave, allowDrop, allowDropFrom, allowDropContainer, dropOver, dropNot, stopPropagation;
    //绑定数据类型,更新属性事件注册

    function allow(ev, target) {
        ev.preventDefault();
    }


    var fieldsets = $("#divData").find("fieldset"),
            radios = fieldsets.find("input[type=radio]"),
            selectDataType, currentDataType;

    (function () {
        fieldsets.on("select", function (e, direction) {
            var children = $(this).children();
            direction ?
                    $(this).children().eq(1).slideDown('fast') :
                    $(this).children().eq(1).slideUp('fast');

        });

        radios.click(function () {
            var $this = $(this);
            $('input[name=radio]').filter(':checked').val();
            currentDataType = $this.data("index");
            (function () {
                window.setTimeout($.proxy(function () {

                    if (currentTable)
                        currentTable.trigger("changeDataType");
                }), 100);

            })()
            radios.removeAttr("checked");
            $this.attr("checked", true);
            fieldsets.each(function (index) {

                $(this).trigger("select", [index == currentDataType]);
            });
        });

        selectDataType = function (index) {
            radios.eq(index).click();
        }
        $("#mabiao").selectpicker({data: {parentId: 100, type: "select"}});

        dropOver = function (e, target) {
            e = e || window.event;
            if (e.preventDefault) {
                e.preventDefault();
                e.stopPropagation();
            } else {
                e.returnValue = false;
                e.cancelBubble = true;
            }

            candrop = true;
            console.log(candrop);
            target.css("background-color", "#00a0e9");

        }
        stopPropagation = function () {
        };
        dropNot = function (e) {
            e = e || window.event;
            if (e.preventDefault) {
                e.preventDefault();
                e.stopPropagation();
            } else {
                e.returnValue = false;
                e.cancelBubble = true;
            }
            candrop = false;
            console.log(candrop);
        }

        dropfinish = function (target) {
            $(target).css("background-color", "transparent");
        }

        dragleave = function (ev, target) {
            ev.preventDefault();
            $(target).css("background-color", "transparent");
        }

        allowDropFrom = function (ev, target) {
            ev.preventDefault();
            console.log("allowDropFrom");
            if (currentObj.data("type") == "form") {
                dropOver(ev, $(target));
            }
            else  dropNot(ev);
        }
        allowDropContainer = function (ev, target) {
            ev.preventDefault();
            console.log("allowDropContainer");
            var $target = $(target);
            var flag = currentObj.data("type") == "table";

            if (currentObj.data("type") == "form") {
                dropNot(ev);
                return;
            }

            if (!flag) {
                currentForm = $target.parent().parent();
                var colNum = getFormColNum();
                if (colNum)
                    flag = true;
            }
            if (flag) {
                if (currentObj[0].tagName == "TH")
                    dropNot(ev);
                else dropOver(ev, $target);
            }
            else dropNot(ev);
        }
        allowDrop = function (ev, target) {
            ev.preventDefault();
            console.log("allowDrop");
            var $target = $(target);

            if (currentObj.data("type") == "table" || currentObj.data("type") == "form") {
                dropNot(ev);
                return;
            }


            if (currentObj[0].tagName == "TH") {
                if ($target.parent().is(currentObj.parent()))
                    dropOver(ev, $target);
                else
                    dropNot(ev);
            }
            else dropOver(ev, $target);
        }

        function bindselect(control, datas) {
            $.each(datas, function (i, val) {
                var option = $("<option>").attr("value", val.value).html(val.name);
                control.append(option);
            });
        }


        bindselect($("#dataType"), datatypes);

    })();

    function unselect() {
        $(".select").removeClass("select");
        $(".table-select").removeClass("table-select");
    }

    var formMainTable, formControl;

    var currentObj, currentTable, tableForm = $("#tableForm").find("tbody"), subForm = $("#subForm").children();

    function getparenttd(td) {
        if (td.parent()[0].tagName.toLowerCase() == "td")
            return td.parent();
        else return getparenttd(td.parent());
    }

    var container = $("#container");


    function getFormColNum(form) {
        if (!form)
            form = currentForm;
        var tmp = {};
        form.trigger("getCol", tmp);
        return tmp.colNum;
    }

    function dropform(ev, target) {
        ev.stopPropagation();
        if (!candrop)return;
        console.log("dropform");
        dropfinish(target);
        var type = currentObj.data("type");
        if (type != "form")return;
        var formTemplate = generateForm()
        currentForm = formTemplate;
        container.append(formTemplate);
        currentForm.trigger("select.form");
    }

    //绑定属性
    var showproperty = {
        control: function (controlType, formObj) {
            formMainTable.css("display", "none");

            if (controlType == "check" || controlType == "radio" || controlType == "select") {
                formControl.find("#divData").css("display", "block");
                if (formObj.definitionData) {
                    selectDataType(formObj.definitionData.type);
                    formObj.definitionData.param1 = formObj.definitionData.param;

                    for (i in formObj.definitionData) {
                        if (i != 'id')
                            formObj[i] = formObj.definitionData[i];
                    }

                }
                tableList.find("tbody").empty();
                if (formObj && formObj.list) {
                    tableList.find("tbody").empty();
                    $.each(formObj.list, function (i, val) {
                        addtr(val);
                    });
                }
            } else {
                formControl.find("#divData").css("display", "none");
            }
            formControl.css("display", "block").trigger("reset").setobject(formObj);
        },
        form: function (formObj, flag) {
            var that = this;
            stopPropagation();
            formMainTable.css("display", "block").trigger("reset").setobject(formObj);
            formControl.css("display", "none");

            if (!currentForm.data("subtable")) {
                templateConfig.parent().parent().css("display", "block");
                if (formObj && formObj.activityForms) {
                    $.each(formObj.activityForms, function (i, val) {
                        templateConfig.children().each(function () {
                            $(this).trigger("setdata", val);
                        })
                    });
                    if (!flag)that.form(formObj, true);

                } else {
                    templateConfig.children().each(function () {
                        $(this).trigger("clear");
                    })
                }
            } else {
                templateConfig.parent().parent().css("display", "none");
            }

        }
    }


    function dropAddCol(ev, th) {
        ev.stopPropagation();
        if (!candrop)return;
        console.log("dropAddCol");
        //th,tr thead table;
        var type = currentObj.data("type");
        var $th = $(th);
        dropfinish(th);
        var obj = {control: $th, index: $th.index(), 'type': type};
        if (type) {
            ($th.parent().parent().parent()).trigger("addCol", obj);
        }
        else {
            ($th.parent().parent().parent()).trigger("moveCol", obj);
        }
    }

    function dropAddrow(ev, div) {
        ev.stopPropagation();
        if (!candrop)return;
        console.log("dropAddrow");
        dropfinish(div);
        var type = currentObj.data("type");
        var div = $(div);

        if (type == "table") {
            generateSubtable(div);
            return;
        }
        var target = div.data("target");
        currentForm = div.parent().parent();
        console.log("currentForm:" + currentForm.length);
        var colNum = getFormColNum();
        if (!colNum)  return;

        var mytr = $("<tr>");
        var width = (100 / colNum) + "%";
        for (i = 0; i < colNum; i++) {
            mytr.append(generateTd(1, 1, width));
        }
        var tbody = div.parent().children().eq(1).children().children();

        if (dragType == DragType.add) {
            switch (target) {
                case 'top':
                {
                    if (tbody.children().length == 0) {
                        tbody.append(mytr);
                    } else {
                        $(tbody.children()[0]).before(mytr);
                    }
                    addField(currentForm, $(mytr.children()[0]), {
                        tagName: type,
                        fieldName: type,
                        fieldDbName: "control" + (controlName++),
                        dataType: 0,
                        colspan: 1
                    });
                    break;
                }
                case  'bottom':
                {
                    tbody.append(mytr);
                    addField(currentForm, $(mytr.children()[0]), {
                        tagName: type,
                        fieldName: type,
                        fieldDbName: "control" + (controlName++),
                        dataType: 0,
                        colspan: 1
                    });
                    break;
                }
            }
            currentForm.trigger("deleterow");
        } else {
            switch (target) {
                case 'top':
                {
                    if (tbody.children().length == 0) {
                        tbody.append(mytr);
                    } else {
                        $(tbody.children()[0]).before(mytr);
                    }
                }
                case  'bottom':
                {
                    tbody.append(mytr);
                }
            }
            mytr.children().eq(0).append(currentObj);
        }
    }

    function drop(ev, td) {
        ev.stopPropagation();
        if (!candrop)return;


        dropfinish(td);
        console.log("drop");
        var type = currentObj.data("type");
        var td = $(td);
        if (!td.is("td"))
            td = td.parent();

        currentForm = td.parents(".widget:first");
        var target = td.data("target");
        if (dragType == DragType.add) {
            if (target)
                td = getparenttd(td);
            addField(currentForm, td, {
                tagName: type,
                fieldName: type,
                dataType: 0,
                fieldDbName: "control" + (controlName++),
                colspan: 1
            }, target == 'left' ? "before" : "after");
            currentForm.trigger("deleterow");
            return;
        }
        var parent = currentObj.parent();

        if (!target) {
            if (td.children().length == 0) {
                td.append(currentObj);
            } else {
                var tdn = generateTd();
                td.after(tdn);
                tdn.append(currentObj);

            }
            currentObj.trigger("colspan");
        }

        if (target) {
            var tdparent = getparenttd(td);

            switch (target) {
                case  'left':
                {
                    if (parent.parent().index() == tdparent.parent().index())
                        if (parent.index() == tdparent.index() - 1 || parent.index() == tdparent.index())
                            return;
                    tdparent.trigger("insertLeft");
                    break;
                }
                case  'right':
                {
                    if (parent.parent().index() == tdparent.parent().index())
                        if (parent.index() == tdparent.index() + 1 || parent.index() == tdparent.index())
                            return;
                    tdparent.trigger("insertRight");
                    break;
                }
            }

        }
        currentForm.trigger("deleterow");
    }

    function updateRowCol() {
        tableForm.children().each(function (row) {
            $(this).children().each(function (col) {
                $(this).find("table").trigger("updatemodel", {'row': row, 'col': col});
            });
        });
    }

    function getMaxCol() {
        var max = 0;
        tableForm.children().each(function (row) {
            var col = 0;
            $(this).children().each(function (col) {
                $(this).find("table").trigger("getcol", col);
            });
            if (col > max)
                max = col;
        });
        return max;
    }

    function drag(ev, cobj, type) {
        ev.stopPropagation();
        dragType = type ? DragType.add : DragType.move;
        currentObj = $(cobj);
    }

    function generateSubtable(div, formobj) {
        var tableForm = subForm.clone();
        var form = generateForm(formobj).attr("data-subtable", "true");
        var content = tableForm.find(".modal-content");
        content.append(form);

        $("body").append(tableForm);

        var t_tableControl = tableForm.find(".widget-body").children().eq(1).children().eq(0);
        var t_tbody = t_tableControl.children();


        var subTableTemplate = $("#subTableTemplate").children().clone();
        if (div.parent().hasClass("widget-body"))
            div.after(subTableTemplate);
        else if (div.hasClass("widget-body"))  div.append(subTableTemplate);
        else div.parent().after(subTableTemplate);

        var gridParm = {
            async: false,
            check: false,
            ispage: false,
            data: [{a: 1}],
            search: false,
            events: {
                editobj: function (obj, parm, i) {

                },
                'deleteobj': function (val, parm, i) {

                }
            }, tools: [{
                text: '新增', event: function (selectItems) {
                    tableForm.modal();
                }
            }]
        };
        subTableTemplate.find("table").table(gridParm);


        function generateTh(parm, from_control, controlType) {
            var obj = parm;


            var th = $("<th draggable='true' ondragstart='drag(event,this)' ondrop='dropAddCol(event,this)' ondragover='allow(event,this)' ondragenter='allowDrop(event,this)' ondragleave='dragleave(event,this)'>");
            //var div = $("<div>");
            //th.append(div);
            th.on("remove.th", function () {

                var index = th.index();
                th.remove();
                subTableTemplate.find("tbody tr").children().eq(index).remove();
                from_control.trigger("remove.control");
            });
            th.on("dataType", function () {
                obj.dataType = $("#dataType").val();
            }).on("required", function () {
                obj.required = $("#required").val();

            }).on("fieldName", function () {
                obj.fieldName = $("#fieldName").val();
                //th.find("div").html(obj.fieldName);
                th.html(obj.fieldName);
            }).on("fieldDbName", function () {
                obj.fieldDbName = $("#fieldDbName").val();
                var index = th.index();
                var tds = subTableTemplate.find("tbody tr").children();
                if (tds.length > index)
                    $(tds[index]).html($.format("${0}$", obj.fieldDbName));
            }).on("click", function (e) {
                th.trigger("select");
                e.stopPropagation();
            }).on("select", function (e) {
                e.stopPropagation();
                unselect();
//                th.find("div").addClass("select");
                th.addClass("select");
                showproperty.control(controlType, obj);
                currentObj = obj;
                formControl.setobject(obj);
                currentTable = th;
                currentTable.reftable = from_control;

            }).on("unselect", function () {
                unselect();
            });
            return th;
        }

        subTableTemplate.on('click', function (e) {
            e. stopPropagation();
            unselect();
            currentForm = form;
            currentForm.trigger("select.form");
            subTableTemplate.addClass("select");
        }).on("remove.sub.form", function () {
            form.trigger("remove.form");
            subTableTemplate.remove();
        }).on("addCol", function (e, obj) {
            var parm = {
                tagName: obj.type || obj.tagName,
                fieldName: obj.type || obj.fieldName,
                fieldDbName: obj.fieldDbName || "control" + (controlName++),
                dataType: obj.dataType || 0,
                colspan: 1 || obj.colspan
            };

            var colNum = getFormColNum(form);
            var t_td = generateTd(1, 1, (100 / colNum) + "%");
            var from_control = addField(form, t_td, obj.tagName ? obj : parm);

            var th = generateTh(parm, from_control, obj.type);
            //th.find("div").html(obj.fieldName || parm.tagName);
            th.html(obj.fieldName || parm.tagName);
            var td = $("<td>");
            if (obj.fieldDbName)td.html($.format("${0}$", obj.fieldDbName));
            var tds = subTableTemplate.find("tbody tr").children();
            var coltd = $(tds[obj.index]);
            var length = subTableTemplate.find("thead tr").children().length;


            if (obj.index == length - 1) {
                obj.control.before(th);
                coltd.before(td);
            } else {
                obj.control.after(th);
                coltd.after(td);
            }
            var t_trs = t_tbody.children();
            if (t_trs.length == 0) {
                t_trs = $("<tr>");
                t_tbody.append(t_trs);
            } else t_trs = $(t_trs[t_trs.length - 1]);
            t_trs.append(t_td);
            from_control.trigger("colspan");

        }).on("moveCol", function (e, obj) {
            var currentIndex = currentObj.index();
            var tds = subTableTemplate.find("tbody tr").children();
            var length = tds.length;
            var currentTd = $(tds[currentIndex]), coltd = $(tds[obj.index]);
            if (obj.index == length - 1) {
                obj.control.before(currentObj);
                coltd.before(currentTd);
            } else {
                obj.control.after(currentObj);
                coltd.after(currentTd);
            }
        }).on("save.sub.table", function (e, pformboj, parent, modal) {
            var test = {}, myparm = {};
            form.trigger("save.form", [pformboj.subform, $(".modal-content", modal), myparm]);
            var name = '';
            var guid = Guid.NewGuid();
            for (i in myparm) {
                name = i;
                gridparms[i] = myparm[i];
                gridparms[i].tools = [{
                    text: '新增',
                    event: $.format("function () {var modal=$('#{0}');\r\ngridparms.{1}.insert=true ;\r\nmodal.trigger('reset') ;\r\nmodal.modal();\r\n}\r\n", guid, name)
                }];
                if (!gridparms[i].events)
                    gridparms[i].events = {};
                gridparms[i].events.editRow = $.format("function (selectItems,parm,index) {var modal=$('#{0}');\r\ngridparms.{1}.insert=false ;\r\ngridparms.{1}.editIndex=index;\r\nmodal.trigger('reset') ;\r\nmodal.setdata(selectItems); \r\nmodal.modal();\r\n}\r\n", guid, name)
                gridparms[i].events.deleteRow = $.format("function (selectItems,parm,index) {if(confirm('确认删除？')){ gridparms.{0}.data.splice(index,1);\r\ngridparms.{0}.ext.refresh() ;}}", name)
            }


            var currentObj = pformboj.subform[pformboj.subform.length - 1];
            var table = subTableTemplate.find("table").clone().removeAttr("style").attr("data-form-name", currentObj.remark).attr("id", currentObj.formName);
            table.find("th").removeAttr("ondragenter draggable ondragstart dropAddCol ondrop ondragover ondragleave data-target");
            table.attr("data-form-target", guid);


            modal.attr("id", guid);
            modal.find("form").append($("#btnSubmit").clone().children());
            modal.find("form .btn-success").attr("id", "btnAdd" + name);


            table.find("th").eq(0).remove();
            table.find("td").eq(0).remove();

            var $thead = table.find("thead");
            var $th = $("<th>").html(currentObj.remark);
            var $tr = $thead.children();
            $tr.before($("<tr>").append($th));
            parent.append(table);
            pformboj.subformList.push(currentObj.formName);
        });
        return subTableTemplate;

    }

    function generateTd(rowspan, colspan, width) {
        if (!rowspan)
            rowspan = 1;
        if (!colspan)
            colspan = 1;
        var td = $("<td   ondrop='drop(event,this)' ondragover='allow(event,this)' ondragenter='allowDrop(event,this)' ondragleave='dragleave(event,this)'>");
        if (width)
            td.css("width", width);
        td.attr({"rowspan": rowspan, "colspan": colspan})
        td.on("insertLeft", function (ev) {
            var tds = td.parent().children();
            var index = td.index();
            var flag = true;
            if (index > 0) {
                var pre = $(tds[index - 1]);
                if (pre.find("table").length == 0) {
                    pre.append(currentObj);
                    pre.attr("colspan", currentObj.colspan);
                    flag = false;
                }
            }
            if (index == 0 || flag) {
                var td1 = generateTd();
                td.before(td1);
                td1.append(currentObj);
                td1.attr("colspan", currentObj.colspan);
                currentObj.trigger("colspan");
            }
        }).on("insertRight", function (ev) {
            var tds = td.parent().children();
            var index = td.index();
            var flag = true;
            if (index + 1 < tds.length - 1) {
                var after = $(tds[index]);
                if (after.find("table").length == 0) {
                    after.append(currentObj);
                    flag = false;
                }
            }
            if (flag) {
                var td1 = generateTd();
                td.after(td1);
                td1.append(currentObj);
                currentObj.trigger("colspan");
            }

        }).on("notneedMove", function (e, colInfo) {
            colspan = parseInt(td.attr("colspan"));

            if (colInfo.colNum + colspan > colInfo._colNum) {
                if (td.find("table").length == 0) {
                    colInfo.move = false;
                    td.remove();
                } else {
                    colInfo.move = true;
                }
            } else {
                colInfo.colNum += colspan;
                colInfo.move = false;
            }

        }).on("getcol", function (e, col) {
            col.colNum += parseInt(td.attr("colspan"));
            if (td.find("table").length == 0) {
                col.empty.count += parseInt(td.attr("colspan"));
                col.empty.controls.push(td);
            }

        }).on("save.td", function (e, formobj, parentContainer, field) {


            var control = td.find("table"), colNum = formobj.colNum, danwei = 12 / colNum;
            var _colspan = td.attr("colspan") * danwei;


            if (control.length > 0) {
                var obj = {};

                var _label = form_label.clone(), _control = form_control.clone();
                _control.addClass($.format(style, _colspan - 1));
                parentContainer.append(_label).append(_control);
                control.trigger("save.table", [obj, _label, _control, field]);
                obj.row = td.parent().index();
                obj.col = td.index();
                obj.insert = obj.id ? false : true;
                formobj.formDefinition.push(obj);


            } else {

                parentContainer.append($("<div class='" + $.format(style, td.attr("colspan") * danwei) + "'>"));

            }

        });
        return td;
    }

    function generateForm(formObj) {
        var formTemplate = divTemplate.find("#formTemplate").children().clone();
        var form = formTemplate.find("form");
        var table = formTemplate.find("table");
        var tbody = table.find("tbody");
        if (!formObj) {
            formObj = {};
            formObj.formName = "form" + (formName++);
        }
        function bindEvent(control) {
            control.on("click", function (e) {
                e. stopPropagation();
                container.find("form").trigger("unselect.form");
                currentForm = control;
                control.trigger("select.form");
            }).on("select.form", function (e) {
                e.preventDefault();
                e. stopPropagation();
                $(this).addClass("select");
                showproperty.form(formObj);
                currentForm = control;
            }).on("unselect.form", function (e) {
                e. stopPropagation();
                unselect();
            }).on("remove.form", function () {
                formTemplate.remove();
                if (formObj.id) {
                    debugger;
                    deleteObj.push({id: formObj.id, type: 'form'});
                }
            }).on("setCol", function (e, colNum) {
                e. stopPropagation();
                formObj.colNum = colNum;
                var width = (100 / formObj.colNum) + "%";
                var tr = table.find("tr"), td = tr.find("td");
                if (tr.length == 1 && td.length == 0) {
                    for (i = 0; i < colNum; i++)
                        tr.append(generateTd(1, 1, width));
                } else {

                }

            }).on("getCol", function (e, colInfo) {
                e. stopPropagation();
                colInfo.colNum = formObj.colNum;
            }).on("deleterow", function (e) {
                e.stopPropagation();
                tbody.children().each(function () {
                    var $this = $(this);
                    var flag = true;
                    $this.children().each(function () {
                        if ($(this).find("table").length > 0) {
                            flag = false;
                            return false;
                        }
                    });
                    if (flag)
                        $this.remove();
                });

            }).on("remark", function (e, remark) {
                e. stopPropagation();
                formObj.remark = remark;
                formTemplate.find(".widget-caption").html(formObj.remark);
            }).on("formName", function (e, formName) {
                e. stopPropagation();
                formObj.formName = formName;
            }).on("saveactivity", function (e, obj) {
                formObj.activityForms = [];
                templateConfig.children().each(function () {
                    $(this).trigger("save", [formObj, obj]);
                });
            }).on("save.form", function (e, result, parentContainer, gridParm) {
                formObj.templateId = pageParm.template.id;
                formObj.formDefinition = [];


                if (!(formObj.formName)) {
                    saveresult.result = false;
                    saveresult.message += "未设置表单名称\r\n";
                }


                formObj.subformList = [];
                if (!formObj.subForm)
                    formObj.subForm = [];


                validate[formObj.formName] = {};
                var myvalidate = validate[formObj.formName];
                myvalidate['fields'] = {};

                if (parentContainer) {
                    validate[formObj.formName].submitHandler =
                            $.format("function(obj,$this){if(gridparms.{0}.insert) gridparms.{0}.data.push(obj);\r\nelse {gridparms.{0}.data[gridparms.{0}.editIndex]=obj }\r\ngridparms.{0}.ext.refresh();\r\n$this.modal('hide');}", formObj.formName);
                    validate[formObj.formName].submitBtn = $.format('btnAdd{0}', formObj.formName);
                    formObj.html = parentContainer;
                }
                else {
                    var div = $("<div>");
                    var formTemplate = divTemplate.find("#formTemplate").children().clone();
                    formTemplate.find("table").remove();
                    formTemplate.removeAttr("ondragenter").removeAttr("ondragover").removeAttr("ondragleave").removeAttr("ondragleave").removeAttr("data-target");
                    formObj.html = div.append(formTemplate);
                    formTemplate.attr("id", formObj.formName);
                    debugger;
                    if (!(formObj.activityForms && formObj.activityForms.length == templateConfig.children().length)) {
                        saveresult.result = false;
                        saveresult.message += $.format("{0}------未设置表单权限\r\n", formObj.formName);
                    }
                }


                if (gridParm) {
                    gridParm[formObj.formName] = {
                        async: false,
                        check: false,
                        ispage: false,
                        search: false
                    };
                }

                formObj.html.find(".widget-header span").html(formObj.remark);
                var form = formObj.html.find("form");
                form.attr("data-form-name", formObj.remark);
                var parent = form.parent();
                parent.html("").append(form);
                form.addClass("form-horizontal");
                formObj.insert = formObj.id ? false : true;
                var tboby = $(this).find("form").find("tbody:first");
                tboby.children().each(function () {
                    var div = $("<div class='form-group'>");
                    form.append(div);
                    $(this).children().each(function () {
                        $(this).trigger("save.td", [formObj, div, myvalidate['fields']]);
                    });
                });
                formObj.subform = [];
                $(this).find("div[data-role=subTableTemplate]").each(function () {
                    var mySubForm = $("#generateModal").clone();
                    mySubForm.removeAttr("id");
                    formObj.html.append(mySubForm);
                    $(this).trigger("save.sub.table", [formObj, form.parent(), mySubForm]);
                });
                //页面加载
                (function () {
                    function generate4() {
                        var permissions = "";
                        $.each(formObj.formDefinition, function (z, definition) {
                            if (definition.jsString) permissions += definition.jsString;
                        });
                        if (formObj.subformList && formObj.subformList.length > 0) {
                            $.each(formObj.subform, function (i, val1) {
                                $.each(val1.formDefinition, function (y, define) {
                                    if (define.jsString) permissions += define.jsString;
                                });
                            });
                            $.each(formObj.subformList, function (i, val1) {
                                permissions += $.format('removeLastCol("{0}");gridparms.{0}.data=formdata.{1}.{0};\r\n$("#{0}").table(gridparms.{0});\r\n', val1, formObj.formName);
                            });
                        }

                        permissions += $.format('$("#{0}").setdata({1}.{0},true);\r\n', formObj.formName, 'formdata');
                        return permissions;
                    }

                    function generate6() {
                        var permissions = "";
                        $.each(formObj.formDefinition, function (z, definition) {
                            if (definition.jsString) permissions += definition.jsString;
                        });
                        if (formObj.subformList && formObj.subformList.length > 0) {
                            $.each(formObj.subform, function (i, val1) {
                                $.each(val1.formDefinition, function (y, define) {
                                    if (define.jsString) permissions += define.jsString;
                                });
                            });
                            $.each(formObj.subformList, function (i, val1) {
                                var formTarget = formObj.html.find("#" + val1).data('formTarget');
                                permissions += $.format('$("#{0}").validate(validateList.{1});\r\n', formTarget, val1)
                                permissions += $.format('gridparms.{0}.data=(formdata&&formdata.{1}&&formdata.{1}.{0})?formdata.{1}.{0}:[];$("#{0}").table(gridparms.{0});\r\n', val1, formObj.formName);
                            });
                        }
                        permissions += $.format('if(formdata&&formdata.{0})$("#{0}").setdata({1}.{0},false);\r\n', formObj.formName, 'formdata');
                        return permissions;
                    }

                    debugger;
                    if (formObj.activityForms) {
                        var permissions = "switch(currentactivity.id){";

                        $.each(formObj.activityForms, function (i, val) {
                            permissions += $.format("case {0}:", val.activityId);
                            switch (val.permissions) {
                                case 4:
                                    permissions += generate4();
                                    break;
                                case 6:
                                    permissions += generate6();
                                    break;
                                case 0:
                                    permissions += $.format(' $("#{0}").remove();', formObj.formName);
                                    break;
                            }
                            permissions += "break;";
                        });
                        permissions += "}\r\n";
                        formObj.permissions = permissions;
                    }
                })()

                result.push(formObj);
            });
        }

        bindEvent(formTemplate);


        if (formObj.remark)
            formTemplate.trigger("remark", formObj.remark);

        formMainTable.css("display", "block").trigger("reset").setobject(formObj);
        return formTemplate;
    }


    var tableList = $("#tableList");

    function addtr(obj) {
        var tr = $($.format("<tr><td>{0}</td><td>{1}</td><td style='width: 52px; padding: 8px 0;'><i class='glyphicon glyphicon-arrow-up' style='margin-right: 5px; cursor: pointer;'></i><i class='glyphicon glyphicon-arrow-down' style='margin-right: 5px; cursor: pointer;'></i><i class='glyphicon glyphicon-remove' style=' cursor: pointer;'></i></td></tr>", obj.key, obj.nameCollect));
        tableList.find("tbody").append(tr);
        var tds = tr.children();
        tr.find("i").click(function () {
            var $this = $(this), index = $this.index();
            switch (index) {
                //上
                case 0:
                    currentTable.trigger("datalist.sort", [tr.index(), "up"]);
                    break;
                //下
                case 1:
                    currentTable.trigger("datalist.sort", [tr.index(), "down"]);
                    break;
                //删除
                case 2:
                    currentTable.trigger("datalist.remove", [tr.index()]);
                    break;
            }
        });
    }

    function addField(form, td, obj, position) {
        debugger;
        var table = divTemplate.find("#tableTemplate").children().clone();
        var tds = table.find("td");
        $(tds[0]).html(obj.fieldName);
        var control;
        switch (obj.tagName) {
            case "check":
                control = controlTemplate.eq(0).clone()
                break;
            case "radio":
                control = controlTemplate.eq(1).clone()
                break;
            default:
                control = $("<" + getvalue(obj.tagName, tags) + " style='background:transparent'>").addClass("form-control").attr("disabled", "disabled");
                if (control.is("input"))
                    control.attr("type", "text");
                break;


        }

        $(tds[1]).empty().append(control);

        if (obj.tagName == "select" || obj.tagName == "check" || obj.tagName == "radio") {
            if (!obj.definitionData)
                obj.definitionData = {type: 0};
            else {
                if (obj.definitionData.localText) {
                    obj.list = $.evalJSON(obj.definitionData.localText);
                }
            }
        }
        table.on("click", function (e) {
            debugger;
            e.stopPropagation();
            currentTable = table;
            showproperty.control(obj.tagName, obj);
            currentObj = obj;
            currentObj.insert = false;

            table.trigger("selectTable");
        }).on("save.table", function (e, controlobj, _label, _control, fields) {
                    for (i in obj) {
                        controlobj[i] = obj[i];
                    }

                    if (!obj.fieldDbName) {
                        debugger;
                        saveresult.result = false;
                        saveresult.message += $.format("{0}----未设置数据库字段 \r\n", obj.fieldName);
                    }
                    if (!obj.fieldName) {
                        debugger;
                        saveresult.result = false;
                        saveresult.message += $.format("{0}----未设置名称 \r\n", obj.tagName);
                    }

                    var myControl = control.clone();
                    myControl.attr("name", obj.fieldDbName).attr("id", obj.fieldDbName).removeAttr("disabled");

                    if (obj.isTitle)
                        instanceName = $.format('return $("#{0}").val();\r\n', obj.fieldDbName);

                    _label.html(obj.fieldName).attr("for", obj.fieldDbName), _control.append(myControl);

                    if (obj.tagName == "select" || obj.tagName == "check" || obj.tagName == "radio") {
                        if (obj.tagName == "check" || obj.tagName == "radio") {
                            myControl.find('span').html("");
                            myControl.removeAttr("id").removeAttr("name");
                            _control.attr("id",obj.fieldDbName);
                        }

                        switch (obj.definitionData.type) {
                            case 2:
                            {
                                controlobj.definitionData.localText = $.toJSON(obj.list);



                                $.each(obj.list, function (i, val) {
                                    switch (obj.tagName) {
                                        case 'select':
                                            var option = $("<option>").attr("value", val.key).html(val.nameCollect);
                                            myControl.append(option);
                                            break;
                                        default:
                                            if (i == 0) {
                                                myControl.find("span").html(val.nameCollect);
                                                myControl.find("input").attr("value", val.key).attr("name", obj.fieldDbName);
                                            }
                                            else {
                                                var next = myControl.clone();
                                                next.find("span").html(val.nameCollect);
                                                next.find("input").attr("value", val.key).attr("name", obj.fieldDbName);
                                                myControl.after(next);
                                            }
                                            break;


                                    }
                                });
                                break;
                            }
                            case 0:
                            {
                                switch (obj.tagName) {
                                    case 'select':
                                        controlobj.jsString = $.format('$("#{0}" ).selectpicker({data: {parentId: {1},type: "select"}});', obj.fieldDbName, obj.definitionData.param);
                                        break;
                                    case 'check':
                                        controlobj.jsString = $.format('$("#{0}" ).checkboxpicker({param:{token: context.token,parentId:"{1}"},name:"{0}",type:0});', obj.fieldDbName, obj.definitionData.param);
                                        break;
                                    case 'radio':
                                        controlobj.jsString = $.format('$("#{0}" ).checkboxpicker({param:{token: context.token,parentId:"{1}"},name:"{0}",type:1});', obj.fieldDbName, obj.definitionData.param);
                                        break
                                }
                                break;
                            }
                            case 1:
                            {
                                break;
                            }


                        }
                    }
                    else if (obj.dataType == datatypes[3].value) {
                        controlobj.jsString = $.format('$("#{0}" ).datetimepicker({ format: "yyyy-mm-dd" });', obj.fieldDbName);
                    } else if (obj.tagName == "textarea") {
                        myControl.attr("rows", "5");
                    }
                    var validators = {};
                    flag = 0;
                    if (obj.required) {
                        validators.notEmpty = {};
                        ++flag;
                    }
                    if (obj.dataType != datatypes[0].value) {
                        $.each(datatypes, function (i, val) {
                            if (val.value == obj.dataType) {
                                validators.dataType = val.name;
                                return false;
                            }
                        });
                        ++flag;
                    }
                    if (flag > 0) {
                        var validateParm = {};
                        validateParm[obj.fieldDbName] = {};
                        validateParm[obj.fieldDbName]["validators"] = validators;
                        fields[obj.fieldDbName] = validateParm[obj.fieldDbName];
                    }
                }
        ).on("remove.control", function () {
            if (obj.id) {
                deleteObj.push({id: obj.id, type: 'control'});
            }
            table.remove();
        }).on("action", function (e, action) {
            if (obj.definitionData)
                obj.definitionData.action = action;
        }).on("fieldText", function (e, fieldText) {
            if (obj.definitionData)
                obj.definitionData.fieldText = fieldText;
        }).on("fieldValue", function (e, fieldValue) {
            if (obj.definitionData)
                obj.definitionData.fieldValue = fieldValue;
        }).on("param", function (e, param) {
            if (obj.definitionData)
                obj.definitionData.param = param;
        }).on("changeDataType", function (e) {
            if (!obj.definitionData)
                obj.definitionData = {};
            obj.definitionData.type = currentDataType;
        }).on("isTitle", function (e, value) {
            if (value == 1) {
                $("*[data-instance-title]").trigger("unTitle");
                table.attr('data-instance-title', '1');
                obj.isTitle = 1;
            } else  obj.isTitle = 0;
        }).on("unTitle", function () {
            obj.isTitle = 0;
            table.removeAttr("data-instance-title");
        }).on("updatemodel", function (e, cobj) {
            obj.row = ++cobj.row;
            obj.column = ++cobj.col;
            table.parent().attr({"rowspan": obj.rowspan, "colspan": obj.colspan});
        }).on("data-required", function () {
            obj.required = $("#required").val();
            console.log(table);
        }).on("dataType", function () {
            obj.dataType = $("#dataType").val();
        }).on("fieldName", function () {
            obj.fieldName = $("#fieldName").val();
            $(tds[0]).html(obj.fieldName);
        }).on("fieldDbName", function () {
            obj.fieldDbName = $("#fieldDbName").val();
        }).on("selectTable", function () {
            unselect();
            table.addClass("table-select");
        }).on("unselect", function () {
            unselect();
        }).on("actionCode", function (e, actionCode) {
            obj.actionCode = actionCode;

        }).on("fieldValue", function (e, fieldValue) {
            obj.fieldValue = fieldValue;
        }).on("datalist.add", function (e, item) {
            if (!obj.list)
                obj.list = [];
            obj.list.push(item);
        }).on("datalist.sort", function (e, index, direct) {
            if (direct == "up" && index > 0) {
                var tmp = obj.list[index - 1];
                obj.list[index - 1] = obj.list[index];
                obj.list[index] = tmp;
            } else if (direct == "down" && index < obj.list.length) {
                var tmp = obj.list[index + 1];
                obj.list[index + 1] = obj.list[index];
                obj.list[index] = tmp;
            }
            showproperty.control(obj.tagName, obj);
        }).on("datalist.remove", function (e, item) {
            if (confirm("确认删除？")) {
                obj.list.splice(item, 1);
                showproperty.control(obj.tagName, obj);
            }

        }).on("colspan", function (ev, currentColspan) {
            try {
                td = table.parent();
                //td  tr tbody table div div
                var _colNum = getFormColNum(form);

                var width = (colspan * 100 / _colNum) + "%";
                if (currentColspan) {
                    var colspan = currentColspan;
                    if (!colspan)
                        colspan = 1;
                    if (colspan < 1) {
                        colspan = 1;
                        $("#colspan").val(1);
                    }
                    if (colspan > _colNum) {
                        colspan = _colNum;
                        $("#colspan").val(_colNum);
                    }
                    obj.colspan = colspan;
                }


                td.attr("colspan", obj.colspan);
                td.css("width", width);
                var tr = td.parent();
                var col = {colNum: 0, empty: {count: 0, controls: []}};
                tr.children().each(function () {
                    $(this).trigger("getcol", col);
                });
                var empty = col.empty;
                col = col.colNum;
                var sub = col - _colNum;
                //变小了
                if (sub < 0) {
                    while (sub < 0) {
                        ++sub;
                        tr.append(generateTd(1, 1, width));
                    }
                }
                else if (sub == 0) {

                }
                //变多了，tr下的td增多，需要将多余的 下移
                else {
                    if (sub <= empty.count) {
                        var tmp = sub;
                        while (tmp > 0) {
                            var deltd = empty.controls.pop();
                            var delcol = parseInt(deltd.attr("colspan"));
                            deltd.remove();
                            tmp -= delcol;
                        }

                        while (tmp < 0) {
                            ++tmp;
                            tr.append(generateTd(1, 1, width));
                        }
                    }
                    else {
                        var flag = false;
                        var trNew = $("<tr>");
                        var colInfo = {move: false, colNum: 0, '_colNum': _colNum};
                        var newcolspan = {colspan: 0};
                        var children = tr.children();
                        var children_length = children.length - 1;


                        children.each(function (index) {
                            function changeLine($td, isend) {
                                if (newcolspan.colspan + parseInt($td.attr("colspan")) > _colNum) {
                                    while (newcolspan.colspan < _colNum) {
                                        tr.append(generateTd(1, 1, width));
                                        ++newcolspan.colspan;
                                    }
                                    var tr1 = $("<tr>");
                                    trNew.after(tr1);
                                    trNew = tr1;
                                    newcolspan.colspan = 0;
                                }
                                newcolspan.colspan += parseInt($td.attr("colspan"));
                                trNew.append($td);
                                if (isend) {
                                    while (newcolspan.colspan < _colNum) {
                                        trNew.append(generateTd(1, 1, width));
                                        ++newcolspan.colspan;
                                    }
                                }
                            }

                            if (!flag) {
                                $(this).trigger("notneedMove", colInfo);
                                if (colInfo.move) {
                                    while (colInfo.colNum < _colNum) {
                                        tr.append(generateTd(1, 1, width));
                                        ++colInfo.colNum;
                                    }
                                    tr.after(trNew);
                                    changeLine($(this), index == children_length);
                                    flag = true;
                                }
                            }
                            else {
                                changeLine($(this), index == children_length);
                            }


                        });

                    }
                }

            } catch (ex) {
                $("#colspan").val("1");
                obj.colspan == 1;
            }
        });

        if (obj.isTitle) {
            table.trigger("isTitle", [1]);
        }


        if (td.find("table").length == 0) {
            obj.colspan = td.attr("colspan") ? td.attr("colspan") : 1;
            td.append(table);
        }
        else {
            var tdNew = generateTd(1, 1, td.css("width"));
            if (position == "before")
                td.before(tdNew);
            else  td.after(tdNew);
            td = tdNew;
            td.append(table);
            currentObj = table;
            currentObj.trigger("colspan");
        }
        return table;
    }

    function getvalue(value, datas) {
        var name = "";
        $.each(datas, function (i, val) {
            if (val.name == value) {
                name = val.type;
                return false;
            }
        });
        return name;
    }

    function removeLastCol(formName) {
        var table = $("#" + formName);
        delete  gridparms[formName].tools;
        var tds = table.find("thead tr").children();
        var length = tds.length - 1;
        var td = tds.eq(length);
        var index = td.index();
        td.remove();
        table.find("tbody tr").children().eq(index).remove();
    }

    wfParm = {
        LoadData: function (workflow) {
            {

            }
        }
    }

    function init() {
        debugger;
        formName = 0, controlName = 0;
        deleteObj = [];
        divTemplate = $("#divTemplate"),
                formMainTable = $("#formMainTable"),
                formControl = $("#formControl");
        formMainTable.css("display", "block");
        formMainTable.on("reset", function () {
            formMainTable.find("input[type=reset]").click();
        });
        formControl.on("reset", function () {
            formControl.find("input[type=reset]").click();
        });

        //绑定Form属性
        (function () {
            var rowNum = $("#rowNum", formMainTable),
                    colNum = $("#colNum", formMainTable),
                    remark = $("#remark", formMainTable),
                    formName = $("#formName", formMainTable);
            remark.on("input", function () {
                currentForm.trigger("remark", remark.val());
            });
            formName.on("input", function () {
                currentForm.trigger("formName", formName.val());
            });

            colNum.on("input", function () {
                currentForm.trigger("setCol", parseInt(colNum.val()));
            });


        })();

        //绑定Control属性
        (function () {

            $("#dataType").change(function () {
                currentTable.trigger("dataType");
            });
            $("#required").change(function () {
                currentTable.trigger("data-required");
                console.log(currentTable);
            });

            $("#fieldName").on("input", function () {
                if (currentTable) {
                    currentTable.trigger("fieldName");
                    if (currentTable.reftable)currentTable.reftable.trigger("fieldName");
                }
            });
            $("#fieldDbName").on("input", function () {
                if (currentTable) {
                    currentTable.trigger("fieldDbName");
                    if (currentTable.reftable)currentTable.reftable.trigger("fieldDbName");
                }
            });
            $("#colspan").on("input", function () {
                if (currentTable) {
                    currentTable.trigger("colspan", [$(this).val()]);
                    if (currentTable.reftable)currentTable.reftable.trigger("colspan", [$(this).val()]);
                }
            });


            $("#actionCode").on("input", function () {
                if (currentTable)  currentTable.trigger("actionCode", $("#actionCode").val());
            });
            $("#dataField").on("input", function () {
                if (currentTable) currentTable.trigger("dataField", $("#dataField").val());
            });
            $("#fieldValue").on("input", function () {
                if (currentTable) currentTable.trigger("fieldValue", $("#fieldValue").val());
            });


            $("#action").on("input", function () {
                if (currentTable)
                    currentTable.trigger("action", $("#action").val());
            });

            $("#fieldText").on("input", function () {
                if (currentTable) currentTable.trigger("fieldText", $("#fieldText").val());
            });

            $("#fieldValue").on("input", function () {
                if (currentTable) currentTable.trigger("fieldValue", $("#fieldValue").val());
            });

            $("#param1").on("input", function () {
                if (currentTable) currentTable.trigger("param", $("#param1").val());
            });
            $("#mabiao").on("change", function () {
                if (currentTable) currentTable.trigger("param", $("#mabiao").val());
            });


            $("#isTitle").on("change", function () {
                if (currentTable)
                    currentTable.trigger("isTitle", [$(this).val()]);

            })

            var nameCollect = $("#nameCollect");
            var key = $("#key");
            $("#addItem").click(function () {
                var obj = {'key': key.val(), 'nameCollect': nameCollect.val()}
                addtr(obj);

                nameCollect.val(""), key.val("");
                currentTable.trigger("datalist.add", obj);
            });

        })();

        templateConfig = $("#templateConfig");
        var tdTemplate = $("#tdTemplate").children();


        $.request('/workflow/template/query/id', {id: pageParm.template.id}, function (tmpList) {

            templateConfig.empty();

            $.each(tmpList.activities, function (i, val) {

                if (val.activityType == 2 || val.activityType == 4) {

                    var tr = $("<tr>");
                    templateConfig.append(tr);
                    tr.append($("<td style='vertical-align: middle'>").html(val.activityName));
                    var td1 = $("<td>").append(tdTemplate.clone());

                    tr.append(td1);
                    var td2 = $("<td>").append(tdTemplate.clone());
                    tr.append(td2);
                    var input1 = td1.find("input"), input2 = td2.find("input");

                    input1.click(function () {
                        currentForm.trigger("saveactivity", ['read']);

                    });
                    input2.click(function () {
                        currentForm.trigger("saveactivity", ['edit']);
                    });
                    tr.on("save", function (e, obj, type) {
                        var edit = input2[0].checked ? 2 : 0, read = input1[0].checked ? 4 : 0;
                        if (type == "edit") {
                            if (edit && !read) {
                                read = 4;
                                input1.click();
                            }
                        }
                        else if (type == "read") {
                            if (edit && !read) {
                                edit = 0;
                                input2.click();
                            }
                        }
                        obj.activityForms.push({
                            activityId: val.id,
                            permissions: read | edit
                        });

                    }).on("setdata", function (e, obj) {
                        if (obj.activityId == val.id) {
                            obj.read = obj.permissions & 4;
                            obj.edit = obj.permissions & 2;
                            obj.read ? (input1.attr("checked", "checked")) : ( input1.removeAttr("checked"));
                            obj.edit ? (input2.attr("checked", "checked")) : ( input2.removeAttr("checked"));
                        }
                    }).on("clear", function () {
                        input1.removeAttr("checked"), input2.removeAttr("checked");
                    });

                }
            });
        });

        $.request('/workflow/form/find/templateId', {id: pageParm.template.id}, function (wf_form) {

            container.html("");
            $.each(wf_form, function (i, val) {
                var formTemplate = generateForm(val);
                container.append(formTemplate);
                var _colNum = val.colNum ? val.colNum : 3, width = 100 / _colNum;
                var table = formTemplate.find("table tbody");
                if (val.formDefinition && val.formDefinition.length > 0) {
                    $.each(val.formDefinition, function (i, definition) {

                        var currentLength = table.children().length - 1;

                        while (currentLength < definition.row) {
                            var tr = $("<tr>");
                            table.append(tr);
                            ++currentLength;
                        }

                        var myTr = table.children().eq(definition.row);
                        currentLength = myTr.children().length - 1;

                        while (currentLength < definition.col) {
                            var td = generateTd(1, definition.colspan, width * definition.colspan + "%");
                            myTr.append(td);
                            ++currentLength;
                        }
                        addField(formTemplate, myTr.children().eq(definition.col), definition);

                    });
                } else {
                    return;
                }

                table.children().each(function () {
                    var $this = $(this);
                    var col = {colNum: 0, empty: {count: 0, controls: []}};
                    $this.children().each(function () {
                        $(this).trigger("getcol", col)
                    });
                    while (col.colNum < _colNum) {
                        ++col.colNum;
                        $this.append(generateTd(1, 1, width + "%"));
                    }
                });

                if (val.subform && val.subform.length > 0) {
                    $.each(val.subform, function (j, sub) {
                        var subform = generateSubtable(formTemplate.find(".widget-body"), sub);
                        if (sub.formDefinition)
                            $.each(sub.formDefinition, function (m, definition) {
                                definition.control = subform.find("th").eq(m);
                                definition.index = m;
                                subform.trigger("addCol", definition);
                            });
                    });
                }
            });
        });
        var divGenerate = $("#divGenerate");
        $("#btnSave").click(function () {
                    saveresult = {
                        result: true,
                        message: ''
                    }
                    instanceName = undefined;
                    if (!confirm("确认保存？\r\n保存将覆盖历史数据！")) {
                        return;
                    }
                    divGenerate.html('');
                    var wf_form = [];
                    validate = {}, gridparm = {};
                    $("#container").children().each(function (i) {

                        $(this).trigger("save.form", [wf_form, null, null]);
                        divGenerate.append(wf_form[i].html.children());
                    });


                    if (!saveresult.result) {

                        alert(saveresult.message);
                        return;
                    }

                    function printObj(obj) {
                        var result = "";
                        for (i in obj) {
                            var currentObj = obj[i], typeofObj = typeof  currentObj;


                            if (currentObj instanceof Array) {
                                result += i + ":[";
                                $.each(currentObj, function (i, val) {
                                    result += $.format("{{0}} ,\r\n", printObj(val));
                                });
                                result = result.substring(0, result.length - 3);
                                result += "],\r\n";
                            }

                            else if (typeofObj == 'function')
                                result += $.format("'{0}':{1},\r\n", i, currentObj.toString());
                            else if (typeofObj == 'string') {
                                if (currentObj.indexOf("function") == 0)
                                    result += $.format("'{0}':{1},\r\n", i, currentObj.toString());
                                else
                                    result += $.format("'{0}':'{1}',\r\n", i, currentObj);
                            }
                            else if (typeofObj == 'boolean')
                                result += $.format("'{0}':{1},\r\n", i, currentObj);

                            else if ($.isEmptyObject(currentObj))
                                result += $.format("'{0}':{},\r\n", i);
                            else   result += $.format("'{0}':{{1}},\r\n", i, printObj(currentObj));
                        }
                        return result.substring(0, result.length - 3);
                    }

                    var myString = $.format("validateList={{0}};\r\n", printObj(validate));


                    myString += $.format("var gridparms={{0}}; \r\n", printObj(gridparms));


                    myString += removeLastCol.toString();

                    var load = "";
                    $.each(wf_form, function (i, val) {
                        load += val.permissions;

                    });

                    if (load)
                        myString += $.format("var wfParm={LoadData:{0},InstanceName:function(){{1}},SaveData:function(data){},rule:function(formdata){return '';}}; \r\n",
                                $.format(" function (workflow, currentactivity, formdata) {{0}\r\n}", load),
                                instanceName ? instanceName : $.format('return "{0}_"+moment(new Date(),"YYYY-MM-DD")', pageParm.template.templateName));

                    $.request("/workflow/form/definition/save", {
                        'deleteObj': deleteObj,
                        listForm: wf_form,
                        html: divGenerate.html() + $.format("<script>{0} <\/script>", myString)
                    }, function () {
                        alert("保存成功");
                        pageParm.form = undefined;
                        loadpage("/views/workflow/form.html");
                    });
                }
        );

        $("#btnBack").click(function () {
            if (confirm("未保存，确认返回？")) {
                pageParm.form = undefined;
                loadpage("/views/workflow/form.html");
            }
        });
        $(document).keydown(function (e) {

            e. stopPropagation();
            if (e.keyCode == 46) {
                debugger;
                var select = $(".select");
                if (select.length == 0)
                    select = $(".table-select");
                if (select.length > 0) {
                    if (confirm("确认删除?")) {
                        select = select.eq(0);
                        if (select.parent().is("th"))
                            select.trigger('remove.th');
                        if (select.is("table"))
                            select.trigger('remove.control');
                        else if (select.is("div")) {
                            if (select.hasClass("widget"))
                                select.trigger('remove.form');
                            else
                                select.trigger('remove.sub.form');
                        }
                    }
                }

            }
        });
    }
</script>
</body>
</html>